
use std::{fs::create_dir_all, path::{absolute, Path, PathBuf}};

use clap::Args;
use serde::{Deserialize, Serialize};
use wtask_base::{cmd::create_file, error::WResult, export::log_info};

use crate::{basic::Empty, task::utils::meta::{WTASK_INSTALL_FILES, WTASK_README}, utils::{AppTrait}};





fn task_local_init(dir: &Path) -> WResult<()> {
    create_dir_all(dir)?;
    // create
    for (&file, data) in WTASK_INSTALL_FILES.iter().zip([
        WTASK_README,
        "{\n    \"name\": \"测试名称\",\n    \"tags\": [\"测试标签1\", \"测试标签2\"],\n    \"args\": {}}",
        "#!/bin/bash\nset -e\n\necho \"`pwd`\"\necho ${wtask_src_path}",
        "#!/bin/bash\nset -e\n\necho \"`pwd`\"",
    ]) {
        let p = dir.join(file);
        if !p.exists() {
            log_info!("Create file {file} ...");
            create_file(&p, data)?;
        }
    }
    log_info!("Task init complete: {dir:?}");
    Ok(())
}




#[derive(Debug, Clone, Serialize, Deserialize, Args)]
pub struct AppTaskInit {
    /// 任务的文件夹路径
    pub(crate) path: String,
}


impl AppTrait for AppTaskInit {
    type Status = ();
    type Res = Empty;

    fn client_handle_before<M: FnMut(bool, String) + Send + Sync>(self, mut msg_func: M, _status: Option<Self::Status>) -> WResult<(Option<Self>, Option<Self::Status>)> {
        let dir = absolute(PathBuf::from(&self.path))?;
        if let Err(e) = task_local_init(&dir) {
            msg_func(true, format!("task local init error: {}", e));
        }
        Ok((None, None))
    }
}

